package com.system.core.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

import org.apache.commons.io.IOUtils;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

@UtilityClass
@Slf4j
public class ProcessExecutor {
	
	public String executeOnceByWin(String cmd,String workdir) {
		String result;
		try {
			String[] cmdA = { "cmd", "/c", cmd };
			Process process = Runtime.getRuntime().exec(cmdA,null,new File(workdir));
			process.waitFor();
			result = IOUtils.toString(process.getInputStream(), "utf-8");
			String error = IOUtils.toString(process.getErrorStream(), "utf-8");
			log.error("perror:{}",error);
			return result.toString();
		} catch (Exception e) {
			return "";
		}
	}
	
	public String[] executeOnce(String cmd,String workdir) {
		StringBuilder result = new StringBuilder();
		StringBuilder error = new StringBuilder();
		String[] allresult = new String[2];
		try {
			String[] cmdA = { "/bin/bash", "-c", cmd };
			Process process = Runtime.getRuntime().exec(cmdA,null,new File(workdir));
//			try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream(),"utf-8"), 1024);){
//				String tmp;
//				while((tmp = br.readLine())!=null){
//					error.append(tmp);
//					error.append("\n");
//				}
//				allresult[0] = error.toString();
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
			try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(),"utf-8"), 1024);){
				String tmp;
				while((tmp = br.readLine())!=null){
					result.append(tmp);
					result.append("\n");
				}
				allresult[1] = result.toString();
			} catch (Exception e) {
				e.printStackTrace();
			}
//			process.waitFor();
			return allresult;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public BufferedReader build(String cmd) {
		try {
			String[] buildCommand = { "cmd", "/c", cmd };
			Process process = new ProcessBuilder(buildCommand).redirectErrorStream(true).start();
			return new BufferedReader(new InputStreamReader(process.getInputStream(), "gb2312"));
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
